<!-- 正文开始 -->
<div class="layui-fluid" id="mediaSearch">
    <div class="layui-card">
        <div class="layui-card-body">
            <div class="layui-form toolbar" lay-filter="mediaSearch">
                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-form-label aw">科室</label>
                        <div class="layui-inline">
                            <select name="deptCode" lay-filter="media-deptCode" >
                                <option value="" data-default=""></option>
                            </select>
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label aw">功能分类</label>
                        <div class="layui-inline">
                            <select name="funType" lay-filter="media-funType">
                                <option value="" data-default=""></option>
                            </select>
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label aw">标题</label>
                        <div class="layui-input-inline">
                            <input name="title" class="layui-input" type="text">
                        </div>
                    </div>
                    <div class="layui-inline">
                        <button class="layui-btn icon-btn btnSearch"><i class="layui-icon">&#xe615;</i>搜索</button>
                        <button class="layui-btn icon-btn btnAdd"><i class="layui-icon">&#xe654;</i>添加</button>
                        <button class="layui-btn icon-btn btnSave layui-btn-normal"><i class="layui-icon layui-icon-ok"></i>保存</button>
                    </div>
                </div>
            </div>
            <div class="mediaTableWrapper">
                <table class="layui-table" id="mediaTable" lay-filter="mediaTable"></table>
            </div>
        </div>
    </div>
</div>

<style>
    #mediaSearch .mediaTableWrapper td[data-field='funType'] .layui-table-cell {
        overflow: visible !important;
    }
    #mediaSearch .mediaTableWrapper td[data-field='deptCode'] .layui-table-cell {
        overflow: visible !important;
    }
    #mediaSearch .aw{
        width: auto;
    }
</style>

<!-- 表格操作列 -->
<script type="text/html" id="tpl-mediaTable-operator">
    {{# if(!!d.id){ }}
    <a class="layui-btn layui-btn-normal layui-btn-xs" data-id="{{d.id}}" lay-event="edit">网页</a>
    <a class="layui-btn layui-btn-xs btn-upload" data-id="{{d.id}}" lay-event="up">上传&nbsp;&nbsp;</a>
    {{# } }}
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>

<!-- 表格状态列 -->
<script type="text/html" id="tpl-mediaTable-status">
    <input type="checkbox" lay-filter="tpl-mediaTable-status" value="{{d.id}}" lay-skin="switch" lay-text="正常|无效"
           {{d.status==1 ? 'checked' : ''}}/>
</script>


<script>
    layui.use(['layer', 'table', 'form', 'http','upload','tools'], function () {
        var $ = layui.jquery;
        var layer = layui.layer;
        var table = layui.table;
        var form = layui.form;
        var http = layui.http;
        var tools = layui.tools;
        var upload = layui.upload;

        var $view = $("#mediaSearch");
        var $tbView = $view.find(".mediaTableWrapper");
        var $deptCode = $view.find("select[name='deptCode']");
        var $funType = $view.find("select[name='funType']");
        var mediaTableIns;
        var orderByClause = "sort";
        var funTypeList;
        var deptCodeList = http.getDeptCodeList();
        var rowIndex,rowId;

        tools.select.deptCodeOptions($deptCode);

        var fnGetSearchParam = function () {
            return {
                orderByClause: orderByClause,
                deptCode: $deptCode.val(),
                funType: $funType.val(),
                title: $view.find("input[name='title']").val()
            };
        };
        var fnGetDeptCodeSelect = function(d){
            if(typeof d === 'undefined'){
                return "";
            }
            return '<select data-id="' + (d.id || '') + '" lay-filter="tpl-mediaTable-select">'
                +tools.select.listToOptions({list:deptCodeList,currValue:d.deptCode})
                +'</select>';
        };
        var fnGetFunTypeSelect = function(d){
            if(typeof d === 'undefined'){
                return "";
            }
            return '<select data-id="' + (d.id || '') + '" lay-filter="tpl-mediaTable-select">'
                +tools.select.listToOptions({list:funTypeList,currValue:d.funType})
                +'</select>';
        };

        var fnRender = function () {
            //渲染表格
            mediaTableIns = table.render({
                id: 'mediaTable',
                elem: '#mediaTable',
                method: 'post',
                contentType: "application/json",
                url: http.base_server + 'media/list',
                where: fnGetSearchParam(),
                page: true,
                cellMinWidth: 100,
                height: 'full-200',
                limits : [10,20,30],
                limit : 20,
                autoSort: false,
                request: {
                    pageName: 'pageNum',
                    limitName: 'pageSize'
                },
                cols: [[
                    {type: 'numbers'},
                    {field: 'deptCode', sort:true, title: '科室',width:140, templet:fnGetDeptCodeSelect},
                    {field: 'funType', sort:true, title: '功能分类',width:100, templet:fnGetFunTypeSelect},
                    {field: 'title', title: '标题',width:300, edit: 'text'},
                    {field: 'fileName', title: '文件名',width:130},
                    {field: 'sort', sort:true,title: '排序',width:50, edit: 'text',align:'center'},
                    {field: 'status', templet: '#tpl-mediaTable-status', title: '状态',width:70, align:"center"},
                    {field: 'operator', toolbar: '#tpl-mediaTable-operator', title: '操作', width: 150,align:'center'},
                    {field: 'updateTime', title: '更新时间',width:100},
                    {field: 'updateByWho', title: '更新人',width:100}
                ]],
                error: function(code,msg){
                    http.fail(code,msg);
                },
                done: function (res, curr, count){
                    fnRenderUpload();
                }
            });
        };

        var fnSearch = function(){
            var param = fnGetSearchParam();
            mediaTableIns.reload({where: param,page: {curr: 1}});
        };
        form.on('select(media-deptCode)',function(data){
            fnSearch();
        });
        form.on('select(media-funType)',function(data){
            fnSearch();
        });

        // 搜索按钮点击事件
        $view.find(".btnSearch").click(function () {
            fnSearch();
        });
        table.on("sort(mediaTable)",function(obj){
            orderByClause = (obj.field || '')+ ' ' + (obj.type || '');
            fnSearch();
        });

        // 添加按钮点击事件
        $view.find(".btnAdd").click(function () {
            var sort = tools.getSortMax(mediaTableIns.getCache()) + 1;
            mediaTableIns.addRow({
                deptCode:$deptCode.val(),
                funType:$funType.find("option:eq(1)").attr("value") || '',
                status:1,
                sort:sort
            });
        });

        // 修改状态
        form.on('switch(tpl-mediaTable-status)', function (obj) {
            var idx = obj.othis.parents("tr:eq(0)").attr("data-index");
            var data = {id: obj.elem.value, status: obj.elem.checked ? 1 : 0};
            mediaTableIns.saveDelta(idx,data);
        });

        table.on('edit(mediaTable)',function (row) {
            var idx = row.tr.attr("data-index");
            var data = {};
            data.id = row.data.id;
            data[row.field] = row.value;
            mediaTableIns.saveDelta(idx,data);
        });
        form.on('select(tpl-mediaTable-select)', function (obj) {
            var field = obj.othis.parents("td:eq(0)").attr("data-field");
            var idx = obj.othis.parents("tr:eq(0)").attr("data-index");
            var data = {id: obj.elem.getAttribute("data-id")};
            data[field] = obj.value;
            mediaTableIns.saveDelta(idx, data);
        });

        $view.find(".btnSave").click(function () {
            var data = mediaTableIns.getDelta();
            if(!data){return;}
            http.post('media/saveBatch',JSON.stringify(data),function(res){
                if(res.ok){
                    if(res.data){
                        layui.each(res.data,function(i,item){
                            item.operator = item.id;
                        })
                    }
                    mediaTableIns.updateCache(res.data);
                    mediaTableIns.resetDelta();
                    if(res.data){
                        layui.each(res.data,function(i,item){
                            fnRenderUpload(item.id);
                        })
                    }
                    http.okMsg(res.msg);
                }
            });
        });

        // 显示编辑框
        var showEditModel = function showEditModel(param) {
            layer.open({
                type: 2,
                area: ['1124px','700px'],
                title: param.title,
                offset: '100px',
                maxmin: false,
                content: http.viewPath + '/tinymce/tinymce.html?v=1',
                success: function (layero, index) {
                    $(layero).children('.layui-layer-content').css('overflow', 'visible');  // 禁止出现滚动条
                    layero.find("iframe")[0].contentWindow.setContent(param.content || '');
                },
                btn: ['保存', '取消'],
                yes: function(index, layero){
                    var val = layero.find("iframe")[0].contentWindow.getContent();
                    if(!val ||$.trim(val).length<=0){
                        return;
                    }
                    http.post('media/saveContent',{id: param.id, val: val, title: param.title},function(res){
                        if(res.ok){
                            mediaTableIns.updateRow(param.rowIndex,{fileName: res.data},false,true);
                            layer.close(index);
                        }
                    });
                },
                btn1: function(index, layero){
                    layer.close(index);
                },
                resizing: function(layero){

                }
            });
        };

        table.on('tool(mediaTable)', function(rowObj) {
            var data = rowObj.data;
            if (rowObj.event === 'edit') { //修改html
                if(typeof data.id === 'undefined'){
                    http.failMsg("请先保存");
                    return;
                }

                http.get('media/getContent',{id:data.id},function(res){
                    if(res.ok){
                        showEditModel({title:data.title,id:data.id,content:res.data,rowIndex:rowObj.tr.attr("data-index"),rowObj:rowObj});
                    }
                });

                return;
            } else if (rowObj.event === 'del') { //删除
                layer.confirm("确定删除该行?",{btn:["确定","取消"]},
                    function(index,obj) {
                        layer.closeAll('dialog');
                        rowObj.del();
                    }
                );
            }
        });

        var fnRenderUpload = function(id){
            var selector = ".layui-table-body .layui-table-cell .btn-upload";
            if(id){
                selector += '[data-id="'+id+'"]';
            }
            $tbView.find(selector).click(function(){
                rowIndex = $(this).parents("tr:eq(0)").attr("data-index");
                rowId = $(this).attr("data-id");
            });
            upload.render({
                elem: $tbView.find(selector)
                , url: http.base_server + 'media/upload/'
                //,auto: false
                , accept: 'file' //普通文件
                //,multiple: true
                //,bindAction: $view.find("button[data-id='btnDoUpload']") //选完文件后不自动上传
                , data: function () {
                    return {id: rowId}
                } //必须是函数
                , exts: 'jpg|png|bmp|gif|jpeg|wav|mp4|mp3||avi|rm|rmi|wmv|asf|asx|rmvb|3gp|mov|m4v|dat|mkv|flv|vob'
                , before: function (obj) {
                    if(typeof rowId === 'undefined'){
                        http.failMsg("RowID不存");
                        return false;
                    }

                    layer.load(2); //上传loading
                    return true;
                }
                , done: function (res) {
                    layer.closeAll('loading'); //关闭loading
                    if (http.ok(res.code)) {
                        mediaTableIns.updateRow(rowIndex,{fileName: res.data},false,true);
                        http.okMsg("上传成功");
                    } else {
                        http.fail(res);
                    }
                },
                error: function (index, upload, status, msg) {
                    layer.closeAll('loading'); //关闭loading
                    http.fail(status, msg);
                }
            });
        };

        http.get('codelist/listItemByName',{listName:'mediaFunType'},function(res){
            funTypeList = res.data;
            tools.select.options($funType,funTypeList);
            form.render('select','mediaSearch');
            if(res.ok) {
                fnRender();
            }
        });

    });

</script>